<template>
    <a-modal
        :keyboard="false"
        :maskClosable="false"
        title="修改密码"
        :open="visible"
        :width="550"
        :closable="initValues.type !== 'force'"
        :cancel-button-props="{ disabled: initValues.type === 'force' }"
        :confirmLoading="loading"
        centered
        @ok="handleSubmit"
        @cancel="handleCancel"
    >
        <a-form layout="vertical">
            <a-row :gutter="16" type="flex" justify="start">
                <a-col :xs="12" :sm="12" :md="24">
                    <a-form-item label="旧密码" v-bind="validateInfos.oldPassword">
                        <a-input v-model:value="modelRef.oldPassword" type="password"></a-input>
                    </a-form-item>
                </a-col>
                <a-col :xs="12" :sm="12" :md="24">
                    <a-form-item label="新密码" v-bind="validateInfos.newPassword">
                        <a-input v-model:value="modelRef.newPassword" type="password"></a-input>
                    </a-form-item>
                </a-col>
                <a-col :xs="12" :sm="12" :md="24">
                    <a-form-item label="再次确认密码" v-bind="validateInfos.confirmedPassword">
                        <a-input v-model:value="modelRef.confirmedPassword" type="password"></a-input>
                    </a-form-item>
                </a-col>
            </a-row>
        </a-form>
    </a-modal>
</template>

<script lang="ts">
    import type { PropType } from 'vue';
    import { defineComponent, reactive, ref, watchEffect, watch } from 'vue';
    import { Form, message } from 'ant-design-vue';
    import { updatePassword } from '@/api/user/account';
    import { cloneDeep } from 'lodash-es';
    import { useUserStore } from '@/store/user';
    import { loginRoutePath } from '@/router/define-meta';
    import type { Rule } from 'ant-design-vue/es/form';

    export default defineComponent({
        props: {
            visible: {
                type: Boolean,
                required: true,
            },
            model: {
                type: Object as PropType<any>,
                default: () => null,
            },
        },
        emits: ['cancel', 'success'],
        setup(props, { emit }) {
            const userStore = useUserStore();

            const loading = ref(false);

            const defaultForm = {
                oldPassword: '',
                newPassword: '',
                confirmedPassword: '',
            };
            const modelRef = reactive<any>(cloneDeep(defaultForm));
            const rulesRef = reactive({
                oldPassword: [{ required: true, message: '请输入旧密码' }],
                newPassword: [{ required: true, message: '请输入新密码' }],
                confirmedPassword: [
                    { required: true, message: '请输入密码' },
                    {
                        validator: (_rule: Rule, value: string) => {
                            if (value === '') {
                                return Promise.reject('请输入密码');
                            } else {
                                if (value !== modelRef.newPassword) {
                                    return Promise.reject('密码输入不一致');
                                }
                                return Promise.resolve();
                            }
                        },
                    },
                ],
            });
            const { validateInfos, resetFields, validate } = Form.useForm(modelRef, rulesRef);
            const roleList = ref<any[]>([]);

            // 记录初始值
            const initValues = reactive<any>({});
            watch(
                () => props.visible,
                () => {
                    Object.assign(initValues, cloneDeep(props.model));
                },
            );
            watchEffect(async () => {
                if (props.visible) {
                    Object.keys(modelRef).forEach(key => {
                        delete modelRef[key];
                    });
                    Object.assign(modelRef, cloneDeep(defaultForm));
                }
            });

            const handleCancel = () => {
                resetFields();
                Object.keys(initValues).forEach(key => {
                    delete initValues[key];
                });
                Object.keys(modelRef).forEach(key => {
                    delete modelRef[key];
                });
                Object.assign(modelRef, cloneDeep(defaultForm));
                emit('cancel');
            };

            const handleLogout = () => {
                userStore.LOGOUT().then(() => {
                    location.replace(`${process.env.VUE_APP_PUBLIC_PATH} + ${loginRoutePath}`.replaceAll('//', '/'));
                });
            };

            const handleSubmit = async () => {
                validate().then(() => {
                    loading.value = true;
                    updatePassword({
                        ...modelRef,
                    })
                        .then(res => {
                            if (res.data) {
                                message.success('操作成功');
                                handleLogout();
                            }
                        })
                        .finally(() => {
                            loading.value = false;
                        });
                });
            };
            return {
                loading,

                modelRef,
                validateInfos,
                resetFields,

                handleSubmit,
                handleCancel,

                initValues,
                roleList,
            };
        },
        components: {},
    });
</script>
